package org.seven.jrdp.biz.t.service;

import java.util.List;

import org.seven.jrdp.biz.t.mapper.TCkMapper;
import org.seven.jrdp.biz.t.mapper.TKqMapper;
import org.seven.jrdp.biz.t.model.TCk;
import org.seven.jrdp.biz.t.model.TKq;
import org.seven.jrdp.commons.exception.BizException;
import org.seven.jrdp.commons.model.Option;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class TCkService {
	@Autowired
	private TCkMapper tCkMapper;
	@Autowired
	private TKqMapper tKqMapper;

	@Transactional(readOnly = true)
	public List<TCk> find() {
		PageHelper.orderBy("ggxh_,cksx_");
		return tCkMapper.selectAll();
	}

	@Transactional(readOnly = true)
	public TCk get(String id) {
		return tCkMapper.selectByPrimaryKey(id);
	}

	@Transactional
	public void insert(TCk tCk) {
		if (get(tCk.getCkmc()) != null) {
			throw new BizException("仓库名称不允许重复");
		}
		if (tCk.getKqks() % 2 != 0) {
			throw new BizException("库区数量必须为2的倍数");
		}
		tCkMapper.insertSelective(tCk);
		for (int i = 1; i <= tCk.getKqsl(); i++) {
			TKq tKq = new TKq();
			tKq.setKqmc(tCk.getCkmc() + i);
			tKq.setCkmc(tCk.getCkmc());
			tKq.setKqsx(tCk.getCksx() * 100 + i);
			tKq.setKqzt("00");
			tKqMapper.insertSelective(tKq);
		}
	}

	@Transactional
	public void delete(String id) {
		Example example = new Example(TKq.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("ckmc", id);
		criteria.andNotEqualTo("kqzt", "00");
		if (tKqMapper.selectCountByExample(example) > 0) {
			throw new BizException("该仓库的库区正在使用中，不允许删除");
		}
		TKq tKq = new TKq();
		tKq.setCkmc(id);
		tKqMapper.delete(tKq);
		tCkMapper.deleteByPrimaryKey(id);
	}

	@Transactional(readOnly = true)
	public List<TKq> findKq(String ckmc) {
		Example example = new Example(TKq.class);
		example.orderBy("kqsx");
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("ckmc", ckmc);
		return tKqMapper.selectByExample(example);
	}
	
	@Transactional(readOnly = true)
	public List<Option> getOption() {
		return tCkMapper.getOption();
	}
}